"""
圆盘仪表盘组件
用于显示CPU、GPU、内存使用率的紧凑仪表盘
"""

from PyQt6.QtWidgets import QWidget, QVBoxLayout, QLabel
from PyQt6.QtCore import Qt, QRectF
from PyQt6.QtGui import QPainter, QPen, QBrush, QColor, QFont, QFontMetrics
from PyQt6.QtCore import QTimer


class CircularGauge(QWidget):
    """圆形仪表盘"""
    
    def __init__(self, title="", max_value=100, parent=None):
        super().__init__(parent)
        self.title = title
        self.max_value = max_value
        self.current_value = 0
        self.setMinimumSize(120, 140)  # 紧凑尺寸
        
    def set_value(self, value):
        """设置当前值"""
        self.current_value = max(0, min(value, self.max_value))
        self.update()
    
    def paintEvent(self, event):
        """绘制仪表盘"""
        painter = QPainter(self)
        painter.setRenderHint(QPainter.RenderHint.Antialiasing)
        
        # 计算尺寸
        width = self.width()
        height = self.height()
        size = min(width, height - 30)  # 为标题留出空间
        
        # 绘制背景圆
        center_x = width // 2
        center_y = (height - 20) // 2 + 10  # 向下偏移为标题留空间
        radius = size // 2 - 5
        
        # 绘制外圆边框
        pen = QPen(QColor(200, 200, 200), 2)
        painter.setPen(pen)
        painter.setBrush(QBrush(QColor(240, 240, 240)))
        painter.drawEllipse(center_x - radius, center_y - radius, radius * 2, radius * 2)
        
        # 绘制进度弧
        percentage = self.current_value / self.max_value
        start_angle = 90 * 16  # 从顶部开始 (90度)
        span_angle = -percentage * 360 * 16  # 顺时针绘制
        
        # 根据使用率设置颜色
        if percentage < 0.5:
            color = QColor(0, 200, 0)  # 绿色
        elif percentage < 0.8:
            color = QColor(255, 165, 0)  # 橙色
        else:
            color = QColor(255, 0, 0)  # 红色
        
        pen = QPen(color, 6)
        painter.setPen(pen)
        painter.drawArc(center_x - radius + 3, center_y - radius + 3, 
                       (radius - 3) * 2, (radius - 3) * 2, start_angle, span_angle)
        
        # 绘制中心文本
        painter.setPen(QColor(0, 0, 0))
        font = QFont("Microsoft YaHei", 14, QFont.Weight.Bold)
        painter.setFont(font)
        value_text = f"{self.current_value:.0f}%"
        painter.drawText(QRectF(center_x - 30, center_y - 15, 60, 30), 
                        Qt.AlignmentFlag.AlignCenter, value_text)
        
        # 绘制标题
        font = QFont("Microsoft YaHei", 9)
        painter.setFont(font)
        painter.setPen(QColor(100, 100, 100))
        painter.drawText(QRectF(0, height - 20, width, 20), 
                        Qt.AlignmentFlag.AlignCenter, self.title)


class CompactGaugeWidget(QWidget):
    """紧凑仪表盘组件 - 包含圆盘和文字信息"""
    
    def __init__(self, title="", max_value=100, parent=None):
        super().__init__(parent)
        self.title = title
        self.max_value = max_value
        self.current_value = 0
        
        self.init_ui()
    
    def init_ui(self):
        """初始化界面"""
        layout = QVBoxLayout(self)
        layout.setContentsMargins(5, 5, 5, 5)  # 紧凑边距
        layout.setSpacing(3)  # 紧凑间距
        
        # 圆盘仪表盘
        self.gauge = CircularGauge(self.title, self.max_value, self)
        layout.addWidget(self.gauge)
        
        # 详细信息标签
        self.detail_label = QLabel("-")
        self.detail_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.detail_label.setStyleSheet("font-size: 10px; color: #666;")
        layout.addWidget(self.detail_label)
    
    def set_value(self, value, detail_text=""):
        """设置值和详细信息"""
        self.current_value = value
        self.gauge.set_value(value)
        self.detail_label.setText(detail_text)


class CompactHardwareMonitor(QWidget):
    """紧凑硬件监控面板 - 垂直排列三个仪表盘"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.init_ui()
    
    def init_ui(self):
        """初始化界面"""
        layout = QVBoxLayout(self)
        layout.setContentsMargins(10, 10, 10, 10)
        layout.setSpacing(8)  # 紧凑间距
        
        # 标题
        title_label = QLabel("💻 硬件监控")
        title_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        title_label.setStyleSheet("""
            font-size: 16px; 
            font-weight: bold; 
            color: #333;
            margin-bottom: 10px;
        """)
        layout.addWidget(title_label)
        
        # CPU仪表盘
        self.cpu_gauge = CompactGaugeWidget("CPU", 100, self)
        layout.addWidget(self.cpu_gauge)
        
        # GPU仪表盘
        self.gpu_gauge = CompactGaugeWidget("GPU", 100, self)
        layout.addWidget(self.gpu_gauge)
        
        # 内存仪表盘
        self.memory_gauge = CompactGaugeWidget("内存", 100, self)
        layout.addWidget(self.memory_gauge)
        
        # 温度信息标签（纯文字显示）
        self.temp_label = QLabel("温度: -")
        self.temp_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.temp_label.setStyleSheet("font-size: 11px; color: #888; margin-top: 5px;")
        layout.addWidget(self.temp_label)
    
    def update_data(self, cpu_usage, gpu_usage, memory_usage, cpu_temp=None, gpu_temp=None):
        """更新监控数据"""
        # CPU信息
        cpu_detail = f"核心使用率"
        self.cpu_gauge.set_value(cpu_usage, cpu_detail)
        
        # GPU信息
        gpu_detail = f"显卡负载"
        self.gpu_gauge.set_value(gpu_usage, gpu_detail)
        
        # 内存信息
        memory_detail = f"内存占用"
        self.memory_gauge.set_value(memory_usage, memory_detail)
        
        # 温度信息
        temp_texts = []
        if cpu_temp is not None:
            temp_texts.append(f"CPU: {cpu_temp}°C")
        if gpu_temp is not None:
            temp_texts.append(f"GPU: {gpu_temp}°C")
        
        if temp_texts:
            self.temp_label.setText(" | ".join(temp_texts))
        else:
            self.temp_label.setText("温度: 未检测")